Component({
    data: {
        min: 0,
        max: 100,
        step: 1,
        value: 0,
        fillWidth: 0,
        thumbPosition: 0
    },
    properties: {},
    ready() {
        this.getOffset();
    },
    methods: {
        onTouchStart(e) {
            this.startTouch(e);
        },

        onTouchMove(e) {
            this.moveTouch(e);
        },

        startTouch(e) {
            const touch = e.touches[0];
            const position = touch.clientX - this.lastTouch;
            this.moveSlider(position);
        },

        moveTouch(e) {
            const touch = e.touches[0];
            const position = touch.clientX - this.lastTouch; //this.data.thumbPosition + (touch.clientX - this.lastTouch);
            this.moveSlider(position);
        },

        moveSlider(position) {
            const maxPosition = this.data.max - this.data.min;
            const ratio = Math.max(0, Math.min(1, position / this.sliderWidth));
            const value =
                this.data.min + Math.round((ratio * maxPosition) / this.data.step) * this.data.step;
            var fillWidth = ratio * this.sliderWidth;
            var sliderWidth = ratio * this.sliderWidth;
            sliderWidth = sliderWidth - 10;
            this.setData({
                value: value,
                fillWidth: fillWidth,
                thumbPosition: sliderWidth < 0 ? 0 : sliderWidth
            });
        },

        getOffset() {
            const query = wx.createSelectorQuery().in(this);
            query
                .select(".slider-container")
                .fields({ rect: true, size: true })
                .exec((res) => {
                    this.sliderWidth = res[0].width;
                    this.lastTouch = res[0].left;
                });
        }
    }
});
